package com.xo.xodemo.service.impl;

import com.github.pagehelper.util.StringUtil;
import com.xo.xodemo.mapper.db1.FileMapper;
import com.xo.xodemo.service.FileService;
import org.apache.commons.io.FilenameUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

@Service
public class FileServiceImpl implements FileService {
    @Value("${file.root.path}")
    private String rootpath;
    @Autowired
    private FileMapper fileMapper;
    @Override
    public String transfer(MultipartFile file) throws IOException {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy/MM");
        String tmp=simpleDateFormat.format(new Date())+"/";
        File savepath = new File(rootpath,tmp);
        if (!savepath.exists()) {
            savepath.mkdirs();
        }
        String fileName=file.getOriginalFilename();
        if(!StringUtil.isEmpty(fileName)){
            String suffix= FilenameUtils.getExtension(fileName);
            String newFileName = UUID.randomUUID().toString().toLowerCase()+"."+suffix;
            tmp=tmp+"/"+newFileName;
            File targetFile = new File(savepath,newFileName);
            file.transferTo(targetFile);
            fileMapper.insert(tmp,fileName,file.getContentType());
            return tmp;
        }
        return null;
    }
    @Override
    public File getimage(String fileaddress) throws IOException {
        File savepath = new File(rootpath,fileaddress);

        return savepath;
    }
}
